package com.example.base.springboot;

import com.alibaba.fastjson.JSONObject;
import com.example.base.app.AppInfo;
import com.example.base.app.AppSecretInfo;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class EncryptionTool {

    // 生成RSA公钥和私钥对
    public static KeyPair generateKeyPair() throws Exception {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048);
        return keyGen.generateKeyPair();
    }

    // 使用公钥加密文字
    public static String encryptText(String plainText, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 使用私钥解密文字
    public static String decryptText(String encryptedText, PrivateKey privateKey) throws Exception {
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes);
    }

    // 将 PublicKey 对象转换为字符串
    public static String publicKeyToString(PublicKey publicKey) {
        return Base64.getEncoder().encodeToString(publicKey.getEncoded());
    }

    // 将字符串转换为 PublicKey 对象
    public static PublicKey stringToPublicKey(String publicKeyString) throws Exception {
        byte[] publicBytes = Base64.getDecoder().decode(publicKeyString);
        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(publicBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(pubKeySpec);
    }

    // 将 PrivateKey 对象转换为字符串
    public static String privateKeyToString(PrivateKey privateKey) {
        return Base64.getEncoder().encodeToString(privateKey.getEncoded());
    }

    // 将字符串转换为 PrivateKey 对象
    public static PrivateKey stringToPrivateKey(String privateKeyString) throws Exception {
        byte[] privateBytes = Base64.getDecoder().decode(privateKeyString);
        PKCS8EncodedKeySpec privateSpec = new PKCS8EncodedKeySpec(privateBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(privateSpec);
    }


    public static String getSecret(AppSecretInfo info) throws Exception {
        PublicKey publicKey=stringToPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj4eEmPACZAVYTsKmEdM7tAz9mC0SDbZq1spTxJLmRFRXZPvSHtoybe7aCY/HdwJ1Q3u9PmE2Pk++SKgdW7Snkmd8KOPLR+AIiQD5+nEQ7t9LOlbvDv/07sn5qjLBPyOhp6BVYmc/8vUEy0U8MVeGiU59nn+gwxe5Tur9pCYw8QqXIS+0yWhsNmyhx1U0rn/X+wUf+msSGHSB1lmWsyhegxlLzujUxDYqLnGRfXb1AoAFgymWwHjKSuMq2gIXlyAEt4i6JGSdnRhEMU2icQNm2xm+divU0uW5WjrVNL0dCT4I1Aupd9LsIgzyT424thfShhc4nPk8n1mLArEvFoxltwIDAQAB");
        String encryStr=encryptText(JSONObject.toJSONString(info),publicKey);
        return encryStr;
    }

    public static AppSecretInfo getSecretInfo(String secret)  {
        try {
            PrivateKey privateKey=getPrivateKey();
            String str=decryptText(secret,privateKey);
            return JSONObject.parseObject(str,AppSecretInfo.class);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    //创建密钥
    public static void main(String[] args) throws Exception {
      //  AppSecretInfo appSecretInfo=getSecretInfo("cZckfvifivVrh2NK6JQmhvHsC6svShey6tT8+f5BJRQ2uUGehLsr132/LmhVMqg0B/xQQxxUSyJiHh70+PtnJbsbxXAyF+OYu69aM3JFGGm1vp+qRenf995e1lW3NTd1zNx0BXJPg3LnAOH8Ca7Fes2qfthMDFO2vyPFE4VtlyE+kKr/H6nX86R7CLVInxBJ6BPcpg5lHtroQ33xWwmJS0veyiL4ZHYmNt/FJVqPMWcjf5i9ss6x4Gq5NV750wXVCBIIr5ixhj7k+HfV/+whdTQ9z/e24hNzBSPZxu95+qQTs0PmcxaPOROiJ98xSxXxj8KwgJa8HrFjhAOOKDPytQ==");
        //String appName=appSecretInfo.getAppName();
        //System.out.println(appName);
        createSecret("base-wx");
    }

    public static void createSecret(String appName) throws Exception {
        AppSecretInfo appSecretInfo=new AppSecretInfo();
        appSecretInfo.setAppName(appName);
        appSecretInfo.setAppVersion("1.10");
        appSecretInfo.setCreateDate(new Date());

        LocalDateTime now = LocalDateTime.now();

        // 获取一个月后的时间
        LocalDateTime oneMonthLater = now.plusMonths(120);
        appSecretInfo.setExpireSecond(oneMonthLater.toInstant(ZoneOffset.UTC).toEpochMilli());
        String str=getSecret(appSecretInfo);
        System.out.println(str);
    }


    private static PublicKey getPublicKey() throws Exception {
        PublicKey publicKey=stringToPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj4eEmPACZAVYTsKmEdM7tAz9mC0SDbZq1spTxJLmRFRXZPvSHtoybe7aCY/HdwJ1Q3u9PmE2Pk++SKgdW7Snkmd8KOPLR+AIiQD5+nEQ7t9LOlbvDv/07sn5qjLBPyOhp6BVYmc/8vUEy0U8MVeGiU59nn+gwxe5Tur9pCYw8QqXIS+0yWhsNmyhx1U0rn/X+wUf+msSGHSB1lmWsyhegxlLzujUxDYqLnGRfXb1AoAFgymWwHjKSuMq2gIXlyAEt4i6JGSdnRhEMU2icQNm2xm+divU0uW5WjrVNL0dCT4I1Aupd9LsIgzyT424thfShhc4nPk8n1mLArEvFoxltwIDAQAB");
        return publicKey;
    }

    private static PrivateKey getPrivateKey() throws Exception {
        PrivateKey privateKey=stringToPrivateKey("MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCPh4SY8AJkBVhOwqYR0zu0DP2YLRINtmrWylPEkuZEVFdk+9Ie2jJt7toJj8d3AnVD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